package com.cedifie.lendapp.ui.loan.act

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.R
import com.cedifie.lendapp.analysis.TestAnalysisAddEvent
import com.cedifie.lendapp.analysis.TestDataLibInvoke
import com.cedifie.lendapp.databinding.ActLoanApplyBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.loan.adapter.CedLoanApplyDaysAdapter
import com.cedifie.lendapp.ui.loan.adapter.CedLoanApplyDetailsAdapter
import com.cedifie.lendapp.ui.loan.impl.CedLoanApplyPresenterImpl
import com.cedifie.lendapp.ui.loan.view.ICedLoanApplyView
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.utils.decoration.GridSpacingItemDecoration
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.mvp.MvpAct
import com.cedifie.lendapp.utils.event.CedEventManager
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.helper.ActivityStackManager
import com.lib.base.utils.log.LogHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/18 15:45
 * @Annotation：贷款申请
 */
class CedLoanApplyAct: MvpAct<ICedLoanApplyView, CedLoanApplyPresenterImpl>(),ICedLoanApplyView {
    lateinit var binding: ActLoanApplyBinding

    //老用户可以选择时间
    private var daysAdapter: CedLoanApplyDaysAdapter? = null
    //明细列表
    private var detailsAdapter: CedLoanApplyDetailsAdapter? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    //是否点击申请贷款，只有主动点击申请按钮才会处理总流程刷新通知
    private var isApplyClick = false
    override fun getCedRootView(): View {
        binding = ActLoanApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): CedLoanApplyPresenterImpl {
        return CedLoanApplyPresenterImpl(this)
    }

    override fun initCedView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.parentLayout.setPadding(0,TitleBarUtil.getStatusBarHeight(),0,0)

        initCedRefreshLayout()
        initCedDaysRecyclerView()
        initCedDetailsRecyclerView()
        EventBus.getDefault().register(this)

        //默认显示不可选贷款额度
        showCedNotOptionalViews()
    }

    override fun initCedListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }

        binding.imgKefu.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER,"LoanApply Page")
        }

        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                binding.textAmount.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                mvpPresenter?.loadCedApplyDataAction()
            }
        })

        //确定
        binding.btnSubmit.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_APPLY_CONFIRM,"")
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()

            isApplyClick = true
            /**
             * 流程
             * 1、需要先通过流程接口，判断订单状态和申请状态
             * 2、创建贷款申请订单
             * 3、创建贷款申请订单成功后再验证总流程，返回首页显示审核状态
             */
            showCedLoading(getString(R.string.loading))
            //发送更新总流程通知
            EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
        }
    }

    override fun initCedData() {
        showCedLoading(getString(R.string.loading))
        mvpPresenter?.loadCedApplyDataAction()
    }


    /* 初始化刷新 */
    private fun initCedRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            mvpPresenter?.loadCedApplyDataAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initCedDaysRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(22f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.recyclerView.layoutManager = layoutManager
        daysAdapter = CedLoanApplyDaysAdapter(binding.recyclerView)
        daysAdapter?.setOnItemChildClickListener { _, _, position ->
            daysAdapter?.let {
                val item = it.getItem(position)
                if (item.optBoolean("isSelect",false)){
                    return@setOnItemChildClickListener
                }
                for (i in 0..< it.itemCount){
                    val model = it.getItem(i)
                    model.put("isSelect",false)
                    if (i == position){
                        model.put("isSelect",true)
                    }
                }
                it.notifyDataSetChanged()
            }
            mvpPresenter?.loadCedApplyDataAction()
        }
        binding.recyclerView.adapter = daysAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initCedDetailsRecyclerView() {
        binding.rvDetails.setHasFixedSize(true)
        binding.rvDetails.isNestedScrollingEnabled = false
        binding.rvDetails.isFocusableInTouchMode = false //不需要焦点
        binding.rvDetails.layoutManager = LinearLayoutManager(this)
        detailsAdapter = CedLoanApplyDetailsAdapter(binding.rvDetails)
        binding.rvDetails.adapter = detailsAdapter
        binding.rvDetails.itemAnimator = DefaultItemAnimator()
        detailsAdapter?.setOnItemChildClickListener{ _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 显示不可选贷款额度
     */
    override fun showCedNotOptionalViews() {
        binding.textChooseAmount.text = getString(R.string.loan_common_loan_amount)
        binding.seekBar.visibility = View.GONE
        binding.amountLayout.visibility = View.GONE
    }

    /**
     * 显示可选贷款额度
     */
    override fun showCedOptionalViews(data: JSONObject) {
        binding.textChooseAmount.text = getString(R.string.loan_apply_choose_amount)
        binding.seekBar.visibility = View.VISIBLE
        binding.amountLayout.visibility = View.VISIBLE

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        mMinProcess = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //颗粒度
        mScale = data.optInt("granularity")

        binding.textMinAmount.text = "$mMinProcess"
        binding.textMaxAmount.text = maxAmount
        //设置最大值
        val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
        binding.seekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.seekBar.progress = showAmount
    }

    /**
     * 设置贷款期限
     */
    override fun showCedLoanDurationList(data: JSONObject) {
        if (daysAdapter?.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    dayList.add(obj)
                }
            }
            daysAdapter?.data = dayList
        }
        when(daysAdapter?.itemCount){
            1 -> {
                binding.textChooseDays.text = getString(R.string.loan_apply_loan_term)
            }
            else -> {
                binding.textChooseDays.text = getString(R.string.loan_apply_choose_term)
            }
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showCedLoadDetailsList(data: JSONObject) {
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textAmount.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                dataList.add(array.optJSONObject(i))
            }
        }
        detailsAdapter?.data = dataList
    }

    /**
     * 贷款申请成功
     */
    override fun showCedLoanApplySuccess() {
        //注销事件监听
        EventBus.getDefault().unregister(this)
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        onIntent(CedLoanApplySuccessAct::class.java)
        launch(Dispatchers.Main){
            delay(500)
            //返回首页
            finish()
        }
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showCedLoanApplyFailed() {
        hideCedLoading()
        //返回首页
        ActivityStackManager.finishAllActivity(CedLoanMainAct::class.java)
    }

    /**
     * 获取老客申请贷款金额
     */
    override fun getCedApplyAmount(): String {
        return binding.textAmount.text.toString()
    }

    /**
     * 获取老客申请贷款期限
     */
    override fun getCedApplyDays(): String {
        var days = ""
        daysAdapter?.let {
            if (it.itemCount > 0){
                for (i in 0..< it.itemCount){
                    val item = it.getItem(i)
                    if (item.optBoolean("isSelect",false)){
                        days = item.optString("day")
                        break
                    }
                }
            }
        }
        return days
    }

    /**
     * 更新总流程完成
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun onRefreshProcessCompleted(event: String){
        LogHelper.e("process refresh success >>>>>>>>>>")
        when(event){
            CedEventType.NOTICE.CED_PROCESS_REFRESHED -> {//总流程刷新完成
                if (isApplyClick){
                    mvpPresenter?.onCedCheckProcessAction()
                    isApplyClick = false
                }
            }
        }
    }

    override fun hideCedLoading() {
        super.hideCedLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_APPLY_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_APPLY_END,"")
        EventBus.getDefault().unregister(this)
    }
}